<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @sort-change="sortChange"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.member_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-input style="display: inline-block; width: 200px; margin-right: 10px" v-model="searchName" clearable placeholder="昵称、姓名、手机号"></el-input>
        <el-input style="display: inline-block; width: 200px; margin-right: 10px" type="number" v-model="excessCount" clearable placeholder="剩余多少餐次界定为即将到期（默认10次）"></el-input>
        <el-switch
          style="margin-right: 10px"
          v-model="showEmpty"
          active-text="显示无昵称会员"
          inactive-text="">
        </el-switch>
        <el-switch
          style="margin-right: 10px"
          v-model="filterZero"
          active-text="过滤剩余0餐次会员"
          inactive-text="">
        </el-switch>
        <el-button type="primary"
                   size="small"
                   @click="handleSearch">搜 索
        </el-button>
        <el-button type="primary"
                   size="small"
                   @click="handleAddExemptTimeBatch">增加豁免次数
        </el-button>
        <el-button type="primary"
                   size="small"
                   v-if="permission.member_sync"
                   @click="handleSync">同步周配餐收件人
        </el-button>
        <el-button type="primary"
                   size="small"
                   v-if="permission.member_sync"
                   @click="handleSyncPackagesCount">同步剩余餐次
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          icon="el-icon-info"
          type="text"
          size="small"
          @click.stop="handleToDetail(row)"
        >查看
        </el-button>
        <el-button
          icon="el-icon-plus"
          type="text"
          size="small"
          @click.stop="handleAddExemptTime(row)"
        >增加豁免次数
        </el-button>
        <el-button
          type="text"
          size="small"
          @click.stop="handlePaymentEdit(row)"
        >余额增加/扣除
        </el-button>
        <el-button
          type="text"
          size="small"
          @click.stop="handleManualOrder(row)"
        >增加餐次
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="isVip">
        <el-tag v-if="row.isVip" type="success">是</el-tag>
        <el-tag v-else type="info">否</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isStop">
        <el-switch
          v-model="row.isStop"
          @change="(value) => isStopChange(value, row)"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="正常"
          inactive-text="停餐"
          :active-value="2"
          :inactive-value="1">
        </el-switch>
      </template>
      <template slot-scope="{row}"
                slot="excessDays">
        <el-tag v-if="row.excessDays === 3" type="primary">{{ row.excessDays }} 天</el-tag>
        <el-tag v-else-if="row.excessDays === 2 || row.excessDays === 1" type="warning">{{ row.excessDays }} 天</el-tag>
        <el-tag v-else-if="row.excessDays === 0" type="danger">{{ row.excessDays }} 天</el-tag>
        <el-tag v-else type="info">{{ row.excessDays }} 天</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isFresh">
        <el-switch
          v-model="row.isFresh"
          @change="(value) => isFreshChange(value, row)"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="2">
        </el-switch>
      </template>
      <template slot-scope="{row}"
                slot="notCoriander">
        <el-switch
          v-model="row.notCoriander"
          @change="(value) => notCorianderChange(value, row)"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="2">
        </el-switch>
      </template>
      <template slot-scope="{row}"
                slot="notPepper">
        <el-switch
          v-model="row.notPepper"
          @change="(value) => notPepperChange(value, row)"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="2">
        </el-switch>
      </template>
      <template slot-scope="{row}"
                slot="notTableware">
        <el-switch
          v-model="row.notTableware"
          @change="(value) => notTablewareChange(value, row)"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="2">
        </el-switch>
      </template>
    </avue-crud>
    <el-dialog title="添加本月超时豁免次数"
               append-to-body
               :visible.sync="addExemptTimeVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="30%">
      <el-form v-model="addExemptTimeForm" ref="form" label-width="80px" class="food-select-form">
        <el-form-item label="次数: ">
          <el-input style="width: 70%" v-model="addExemptTimeForm.time"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="余额管理"
               append-to-body
               :visible.sync="paymentVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="30%">
      <el-form v-model="paymentForm" ref="form" label-width="80px" class="food-select-form">
        <el-form-item label="类型: " label-width="120px">
          <div>
            <el-select v-model="paymentForm.type" placeholder="请选择增加或扣除">
              <el-option value="1" label="增加">增加</el-option>
              <el-option value="2" label="扣除">扣除</el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="金额: " label-width="120px">
          <div>
            <el-input style="width: 70%" type="number" v-model="paymentForm.amount" placeholder="请输入金额"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="备注: " label-width="120px">
          <div>
            <el-input style="width: 70%" type="textarea" v-model="paymentForm.remark" placeholder="请输入备注"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePaymentClose">取 消</el-button>
        <el-button type="primary" @click="handlePaymentConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="人工下单"
               append-to-body
               :visible.sync="orderVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="30%">
      <el-form :model="orderForm" ref="form" label-width="80px" class="food-select-form">
        <el-form-item label="套餐: ">
          <el-select style="width: 70%;" v-model="orderForm.packagesId" placeholder="请选择套餐" @change="handlePackagesChange">
            <el-option
              v-for="item in packagesList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <div v-if="Object.keys(packagesSelected).length !== 0">
            <div>
              描述：{{ packagesSelected.description }}
            </div>
            <div>
              每餐单价：￥{{ packagesSelected.price }}
            </div>
            <div>
              是否单餐：{{ packagesSelected.isSingle === 1 ? '单餐' : '多餐' }}
            </div>
            <div>
              餐时数：{{ packagesSelected.effectiveCount }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="份数: ">
          <el-input style="width: 70%;" type="number" v-model="orderForm.count" @change="handlePackagesChange(orderForm.packagesId)"></el-input>
        </el-form-item>
        <el-form-item label="金额: ">
          <el-tag type="danger">￥{{ orderComputeAmount }}</el-tag>
        </el-form-item>
        <el-form-item label="备注: ">
          <el-input style="width: 70%;" type="textarea" v-model="orderForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleOrderCancel">取 消</el-button>
        <el-button type="primary" @click="handleOrderConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, isStopChange, isFreshChange, notPepperChange, notCorianderChange, addExemptTime, addExemptTimeBatch, notTablewareChange, syncPackagesCount} from "@/api/member/member";
  import { add as addPayment} from "@/api/member/member_payment";
  import { manualOrder, getChangeAmount} from "@/api/packages/packages_order";
  import {getSelect as getPackagesList} from "@/api/packages/packages";
  import {mapGetters} from "vuex";
  import { sync } from "@/api/member/member_package_cycle";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: false,
          addBtn: true,
          refreshBtn: false,
          editBtn: true,
          selection: true,
          column: [
            {
              label: "昵称",
              prop: "nickname",
            },
            {
              label: "姓名",
              prop: "name",
            },
            {
              label: "头像",
              prop: "avatar",
              dataType: 'string',
              type: 'upload',
              span: 24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
                name: 'originalName'
              },
              limit: 1,
              action: '/api/blade-resource/oss/endpoint/put-file'
            },
            {
              label: "手机",
              prop: "phone",
              rules: [{
                required: true,
                message: "请输入手机",
                trigger: "blur"
              }]
            },
            {
              label: "是否停餐",
              prop: "isStop",
              width: 150,
              display: false,
              slot: true,
            },
            // {
            //   label: "忌口香菜",
            //   rfttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttprop: "notCoriander",
            //   display: false,
            //   slot: true,
            // },
            // {
            //   label: "忌口辣",
            //   prop: "notPepper",
            //   display: false,
            //   slot: true,
            // },
            // {
            //   label: "不要餐具",
            //   prop: "notTableware",
            //   display: false,
            //   slot: true,
            // },
            // {
            //   label: "是否生鲜",
            //   prop: "isFresh",
            //   display: false,
            //   slot: true,
            // },
            {
              label: "剩余餐次",
              prop: "effectivePackagesCount",
              sortable: true,
              display: false,
            },
            {
              label: "账户余额",
              prop: "amount",
              sortable: 'custom',
              display: false,
            },
            // {
            //   label: "剩余豁免次数",
            //   prop: "exemptTime",
            //   display: false,
            // },
            {
              label: "预计到期日期",
              prop: "expectExpireDate",
              display: false,
              slot: true,
            },
            {
              label: "预计可选餐天数",
              prop: "excessDays",
              display: false,
              slot: true,
            },
            // {
            //   label: "生日",
            //   prop: "birthday",
            // },
            {
              label: "性别",
              prop: "sex",
              type: "select",
              value: 1,
              dicData: [
                {
                  label: "男",
                  value: 1
                },
                {
                  label: "女",
                  value: 2
                },
                {
                  label: "未知",
                  value: 3
                }
              ],
            },
            {
              label: "注册时间",
              prop: "createTime",
              display: false,
            },
          ]
        },
        data: [],
        orderAmount: '',
        showEmpty: false,
        filterZero: true,
        addExemptTimeVisible: false,
        addExemptTimeForm: {
          time: 1
        },
        paymentVisible: false,
        paymentForm: {
        },
        orderVisible: false,
        orderType: '',
        orderForm: {
          count: 1
        },
        orderComputeAmount: 0,
        packagesList: [],
        packagesSelected: {},
        searchName: '',
        excessCount: 10,
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: true,
          viewBtn: this.vaildData(this.permission.member_view, false),
          delBtn: false,
          editBtn: this.vaildData(this.permission.member_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleSync() {
        sync()
      },
      handleSyncPackagesCount() {
        syncPackagesCount()
      },
      handleSearch() {
        this.page.currentPage = 1
        this.onLoad(this.page)
      },
      handleManualOrder(row) {
        this.orderVisible = true
        this.orderType = 1
        this.orderForm.memberId = row.id
        this.loadPackages()
      },
      handleOrderCancel() {
        this.orderForm = {
          count: 1
        }
        this.orderComputeAmount = 0
        this.orderVisible = false
        this.packagesList = []
        this.packagesSelected = {}
        this.onLoad(this.page)
      },
      loadPackages() {
        getPackagesList().then((res) => {
          this.packagesList = res.data.data
          if (this.orderType === 2) {
            this.orderForm.packagesId = this.form.activePackagesId
            this.handlePackagesChange(this.form.activePackagesId)
          }
        })
      },
      handleOrderConfirm() {
        const params = this.orderForm
        manualOrder(params).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.handleOrderCancel()
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
        })
      },
      handlePackagesChange(val) {
        this.packagesList.forEach(item => {
          if (item.id === val) {
            this.packagesSelected = item
          }
        })
        const count = this.orderForm.count ? this.orderForm.count : 1
        this.orderComputeAmount = 0
        getChangeAmount(val, this.orderForm.memberId, count).then(res => {
          this.orderComputeAmount = res.data.data
        })
      },
      sortChange(column) {
        this.orderAmount = ''

        let order = ''
        switch (column.order) {
          case 'ascending':
            order = 'ASC'
            break;
          case 'descending':
            order = 'DESC'
            break;
          default:
            order = ''
            break
        }

        if (column.prop === 'amount') {
          this.orderAmount = order
        }
        this.onLoad(this.page)
      },
      isStopChange(val, row) {
        isStopChange(row.id).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      isFreshChange(val, row) {
        isFreshChange(row.id).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      notCorianderChange(val, row) {
        notCorianderChange(row.id).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      notPepperChange(val, row) {
        notPepperChange(row.id).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      notTablewareChange(val, row) {
        notTablewareChange(row.id).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
      },
      handleClose() {
        this.addExemptTimeForm.memberId = ''
        this.addExemptTimeForm.time = 1
        this.addExemptTimeVisible = false
        this.onLoad(this.page)
      },
      handleConfirm() {
        if (this.addExemptTimeForm.memberId && this.addExemptTimeForm.memberId !== '') {
          addExemptTime(this.addExemptTimeForm.memberId, this.addExemptTimeForm.time).then(() => {
            this.handleClose()
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          })
        } else if (this.ids.length !== 0) {
          addExemptTimeBatch(this.ids, this.addExemptTimeForm.time).then(() => {
            this.handleClose()
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          })
        } else {
          this.$message.warning('请选择要操作的客户')
        }
      },
      handleAddExemptTime(row) {
        this.addExemptTimeVisible = true
        this.addExemptTimeForm.memberId = row.id
      },
      handleAddExemptTimeBatch() {
        if (this.ids.length === 0) {
          this.$message.warning('请选择要操作的客户')
          return
        }
        this.addExemptTimeVisible = true
      },
      handlePaymentEdit(row) {
        this.paymentVisible = true
        this.paymentForm.memberId = row.id
        this.paymentForm.origin = 2
      },
      handlePaymentClose() {
        this.paymentVisible = false
        this.paymentForm = {}
        this.onLoad(this.page)
      },
      handlePaymentConfirm() {
        if (!this.paymentForm.amount || this.paymentForm.amount === '' || this.paymentForm.amount === 0) {
          this.$message.warning('请输入金额')
          return
        }
        const params = this.paymentForm
        addPayment(params).then(() => {
          this.handlePaymentClose()
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      handleToDetail(row) {
        this.$router.push({path: `/memberDetail?id=${row.id}` })
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        if (this.orderAmount && this.orderAmount !== '') {
          params.orderAmount = this.orderAmount
        }
        if (this.searchName && this.searchName !== '') {
          params.searchName = this.searchName
        }
        if (this.showEmpty && this.showEmpty !== '') {
          params.showEmpty = this.showEmpty
        }
        if (this.filterZero && this.filterZero !== '') {
          params.filterZero = this.filterZero
        }
        params.isSoonExpire = true
        if (this.excessCount && this.excessCount !== '') {
          params.excessCount = this.excessCount
        }
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style scoped>
.el-select-dropdown .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0 20px !important;
}
</style>
